package me.zhengjie.modules.easycode.rest;

/**
 * @author guoqing
 * @date 2021/6/13 4:07
 * 授权、根据token获取用户详细信息
 */

import cn.hutool.core.util.ObjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.rest.AnonymousPostMapping;
import me.zhengjie.modules.easycode.domain.EasyCodeUser;
import me.zhengjie.modules.easycode.domain.Project;
import me.zhengjie.modules.easycode.service.ProjectService;
import me.zhengjie.modules.easycode.service.dto.EasyCodeAuthUserDto;
import me.zhengjie.modules.security.config.bean.SecurityProperties;
import me.zhengjie.modules.security.security.TokenProvider;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.utils.Result;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Zheng Jie
 * @date 2018-11-23
 * 授权、根据token获取用户详细信息
 */
@Slf4j
@RestController
@RequestMapping("/bamboo/easycode")
@RequiredArgsConstructor
@Api(tags = "easyCode：接口授权")
public class EasyCodeAuthorizationController {

    private final SecurityProperties properties;
    private final TokenProvider tokenProvider;
    private final UserDetailsService userDetailsService;
    private final ProjectService projectService;
    private final static String NEW_PROJECT_CODE = "new";

    @ApiOperation("登录授权")
    @AnonymousPostMapping(value = "/login")
    public Result login(@Validated @RequestBody EasyCodeAuthUserDto authUser, HttpServletRequest request) throws Exception {
        // 密码解密
        UserDetails userDetails = userDetailsService.loadUserByUsername(authUser.getUsername());
        Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = tokenProvider.createToken(authentication);
        final JwtUserDto jwtUserDto = (JwtUserDto) authentication.getPrincipal();
        final EasyCodeUser user = EasyCodeUser.conversion(properties.getTokenStartWith() + token, jwtUserDto);
        if (NEW_PROJECT_CODE.equals(authUser.getProjectCode())) {
            final Project project = projectService.createProject();
            user.setProjectCode(project.getProjectCode());
        } else {
            final Project project = projectService.getByProjectCode(authUser.getProjectCode());
            if (ObjectUtil.isEmpty(project)) {
                return Result.error("该项目不存在");
            }
            user.setProjectCode(project.getProjectCode());
        }
        return Result.success(user);
    }


}
